<template>
  <el-dialog
    :visible.sync="visible"
    ref="moveDialog"
    custom-class="moveDialog"
    :append-to-body="appendToBody"
    :before-close="beforeClose"
    :width="width"
    :modal="modal"
    :modal-append-to-body="modalAppendToBody"
    :close-on-click-modal="closeOnClickModal"
    :close-on-press-escape="closeOnPressEscape"
    :show-close="showClose"
    :destroy-on-close="destroyOnClose"
    >
    <div slot="title" class="moveDialogTitle" @mousedown="addResizeEvent">
      <slot name="title">
        {{ title }}
      </slot>
    </div>
    <slot></slot>
    <span slot="footer" class="dialog-footer">
      <slot name="footer"></slot>
    </span>
  </el-dialog>
</template>

<script lang="ts">
/**
 * 可拖动的dialog
 * 使用参数参考elementUI el-dialog
 */
import { Component, Vue, Prop, Ref } from 'vue-property-decorator';
@Component({
  name: 'MoveDialog'
})
export default class MoveDialog extends Vue {
  @Ref() private moveDialog
  @Prop({ default: () => false }) private visible
  @Prop({ default: () => '' }) private title
  @Prop({ default: () => '30%' }) private width
  @Prop({ default: () => true }) private appendToBody
  @Prop({ default: () => true }) private modal
  @Prop({ default: () => true }) private modalAppendToBody
  @Prop({ default: () => false }) private closeOnClickModal
  @Prop({ default: () => false }) private closeOnPressEscape
  @Prop({ default: () => true }) private showClose
  @Prop({ default: () => false }) private destroyOnClose
  @Prop() private beforeClose

  private addResizeEvent (e) {
    const el = this.moveDialog.$el.firstElementChild
    const elW = el.clientWidth
    const elH = el.clientHeight
    const windowW = document.documentElement.clientWidth
    const windowH = document.documentElement.clientHeight
    e.stopPropagation()
    const disx = e.pageX - el.offsetLeft
    const disy = e.pageY - el.offsetTop
    document.onmousemove = (ev) => {
      ev.preventDefault()
      let x = ev.pageX - disx
      if (x < elW / 2) {
        x = elW / 2
      }
      if (x > windowW - elW / 2) {
        x = windowW - elW / 2
      }
      let y = ev.pageY - disy
      if (y < elH / 2) {
        y = elH / 2
      }
      if (y > windowH - elH / 2) {
        y = windowH - elH / 2
      }
      el.style.left = x + 'px'
      el.style.top = y + 'px'
    }
    document.onmouseup = () => {
      document.onmousemove = document.onmouseup = null
    }
  }
}
</script>

<style lang="stylus">
.moveDialog {
  position: absolute
  top 50%
  left 50%
  transform: translate(-50%, -50%)
  margin-top 0px !important
}
.moveDialogTitle {
  position: absolute;
  width: 100%;
  height: 60px;
  top: 0;
  left: 0;
  line-height: 60px;
  padding: 0px 24px;
  font-size: 16px;
  cursor: move;
  color: #303753;
  font-weight: 600;
}
</style>
